//
//  AllproductsViewController.swift
//  NewLndd
//
//  Created by 邵禹曦 on 2019/12/31.
//  Copyright © 2019 辽宁当代. All rights reserved.
//

import UIKit

// MARK: - 全部商品
class AllproductsViewController: HomeApiViewController, UITableViewDelegate,UITableViewDataSource {
    
    // MARK: - 懒加载属性
    private lazy var titleBtn : TitleButton = TitleButton()
    // 定义数组  Use of undeclared type 'Status'  数组 : [模型Model]
    private lazy var ViewModels : [Allproducts] = [Allproducts]()

    var newsArray : NSArray = []
    // 挂单
    @IBOutlet weak var gd: UIButton!
    // 商品信息
    @IBOutlet weak var spxx: UIButton!
    // 商品订购
    @IBOutlet weak var spdg: UIButton!
    
    @IBOutlet weak var TableView: UITableView!

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 用户验证
        showInfo()
 
        
        
        
    }
    

    
}

// MARK: - 用户验证
extension AllproductsViewController {
    private func showInfo() {
        // GCD
        let  group = DispatchGroup()
 
        // 从沙盒中获取参数
         var userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
         userPath =  (userPath as NSString).appendingPathComponent("data.plist")
         user = NSKeyedUnarchiver.unarchiveObject(withFile: userPath) as? User
        print(userPath)
        Thread.sleep(forTimeInterval: 0.05)

        // 用户验证
        self.u = user?.U!
        self.retcode = user?.RETCODE!
        // 用户验证
        let str = [u,"101",retcode]

        group.enter()
        NetworkTools.share.check_user(code: str as Array<Any>) { (result, error) in
                      
                          if error != nil {
                              print("no no no")
                              return
                          }
            print(result!)
            if(result?["error"] != nil) {
                print(result!["error"]!)
                if #available(iOS 13.0, *) {
                    self.showMsgbox(_message: "数据请求失败")
                    self.isLogin = false
                    return self.setupVisitorView()
                }
            }
                          

                          if Int(self._retcode(res: result!))! < 0 {
                            
                              self.isLogin = false
                          } else {
                              self.isLogin = true
                          }
                          group.leave()
                      }

        group.notify(queue: DispatchQueue.main) {

            if !self.isLogin {
                if #available(iOS 13.0, *) {
                    self._alertVisitorView()
                }
                return
            } else {
                // 2.设置导航栏内容
                self.setupNavigationBar()
            }
         }
        
    }
}



// MARK: - 设置UI界面
extension AllproductsViewController {
    
    private func setupNavigationBar() {
        
        // 1.设置右侧item  暂时放着
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "注销", style: .plain, target: self, action: #selector(goLogoffBtnClick))
            
        // 2.设置titleView
        titleBtn.setTitle("游客", for: .normal)
        titleBtn.addTarget(self, action: #selector(titleBtnClick), for: .touchUpInside)
        // 执行按钮
        navigationItem.titleView = titleBtn
        Thread.sleep(forTimeInterval: 0.05)
        // 行情
        loadcommodity_data_query(con: "0")
        
        // 监听按钮
        gd.addTarget(self, action: #selector(topBtn), for: .touchUpInside)
        spxx.addTarget(self, action: #selector(topBtn1), for: .touchUpInside)
        spdg.addTarget(self, action: #selector(topBtn2), for: .touchUpInside)
        
    }
}


// MARK: - 事件监听函数
extension AllproductsViewController {
    
    @objc private func titleBtnClick(titleBtn : TitleButton!) {
        // 1.改变按钮的状态
        //titleBtn.isSelected = !titleBtn.isSelected
        
        // 2.创建弹出控制器
    }
    
    @objc private func topBtn() {
        self.performSegue(withIdentifier: "gdmm", sender: nil)
    }
    
    @objc private func topBtn1() {
        self.performSegue(withIdentifier: "cominfo", sender: nil)
    }
    
    @objc private func topBtn2() {
        self.performSegue(withIdentifier: "spdg", sender: nil)
    }
    //user_logoff
    @objc private func goLogoffBtnClick() {
        let u = self.u!
        let sid = self.retcode!
        let str = [u, sid]
        NetworkTools.share.user_logoff(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            print(result!)
            if Int(self._retcode(res: result!))! >= 0 {
                // 重置解包
                let arr = ["U" : "", "RETCODE" : ""]
                let user = User(dict: arr as [String : AnyObject])
                user.U = arr["U"]
                user.RETCODE = arr["RETCODE"]
                
                // 获取沙盒路径
                var userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
                userPath = (userPath as NSString).appendingPathComponent("data.plist")
                // 保存对象
                NSKeyedArchiver.archiveRootObject(user, toFile: userPath)
                
                if #available(iOS 13.0, *) {
                    self.showMsgbox(_message: "注销成功")
                    self.isLogin = false
                    return self.setupVisitorView()
                }
                
            } else {
                if #available(iOS 13.0, *) {
                    self.showMsgbox(_message: "注销失败")
                }
            }
        }
    }
}


// MARK: - 行情
extension AllproductsViewController {
    
    // 获取当前页的接口数据： 行情接口
    @objc private func loadcommodity_data_query(con : String)
    {
        // 行情 - 全部商品
        let str = [con]
        NetworkTools.share.sell_commodity_query(code: str as Array<Any>) { (result, error) in
            
            // 错误校验
            if error != nil {
                print("\(String(describing: error))")
                return
            }
            //print(result!)
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            print(self.isLogin)
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) < 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "数据加载失败")
                            return self.setupVisitorView()
                        }
                    }
                }
            }
            
            
            // 调用模型
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULTLIST"] as? [String : AnyObject]   {
                    for temp in arr["REC"] as! NSArray {
                        let sta = Allproducts(dict: temp as! [String : AnyObject])
                        self.ViewModels.append(sta)
                    }
                    // 刷新表格
                    self.TableView.reloadData()
                }
            }
            
            
            
        }
    }
}




// MARK: - TableView的数据源方法
extension AllproductsViewController
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.ViewModels.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         // 创建cell  AllmerchandiseCellId
        let cell : AllproductsViewCell = tableView.dequeueReusableCell(withIdentifier: "AllproductsViewCellId") as! AllproductsViewCell
        
        cell.ViewModel = ViewModels[indexPath.row]
        
        cell.m3gdBtn.tag = indexPath.row
        cell.m3gdBtn.addTarget(self, action: #selector(m3gdBtn), for: .touchUpInside)
        
        cell.m4gdBtn.tag = indexPath.row + 100000
        cell.m4gdBtn.addTarget(self, action: #selector(m4gdBtn), for: .touchUpInside)
        
        
        
        return cell
    }
    
    // cell高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 260
    }
    
    // UITableViewDelegate 方法，处理列表项的选中事件
    
    // 是不是跳转绑定view了，数过不去
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.TableView.deselectRow(at: indexPath, animated: true)
        // prepare 传参
        //self.performSegue(withIdentifier: "mgd", sender: indexPath)
    }
    
    
    
    

}



// MARK: - TableView Btn
extension AllproductsViewController {
    
    @objc private func m3gdBtn(sender : UIButton!) {
        let tag = sender.tag
        self.ViewModels[tag].sta = "1"
        self.performSegue(withIdentifier: "mgd", sender: self.ViewModels[tag])
        
    }
    
    @objc private func m4gdBtn(sender : UIButton!) {
        let tag = sender.tag - 100000
        self.ViewModels[tag].sta = "2"
        self.performSegue(withIdentifier: "mgd", sender: self.ViewModels[tag])
        //print(self.ViewModels[tag].sta)
        
    }
    
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // 买挂单
        if segue.identifier == "mgd" {
            let secVC = segue.destination as! BuyingalistViewController
            if let allIndexPath = sender as? Allproducts {
                secVC.Product = allIndexPath
            }
        }
        
        // 挂单买，卖
        if segue.identifier == "gdmm" {
            let secVC = segue.destination as! putUpViewController
            if let putIndexPath = sender as? putUpView {
                secVC.put = putIndexPath
            }
        }
        
        // 商品信息
        if segue.identifier == "cominfo" {
            let secVC = segue.destination as! comInfoViewController
            if let putIndexPath = sender as? putUpView {
                secVC._comInfo = putIndexPath
            }
        }
        
        // 商品信息
        if segue.identifier == "spdg" {
            let secVC = segue.destination as! comSendViewController
            if let putIndexPath = sender as? putUpView {
                secVC._spdg = putIndexPath
            }
        }
    }
}
